/**
 * 
 */
package cultu.supplier.service.impl;

import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.transaction.annotation.Transactional;

import cultu.common.message.User;
import cultu.common.message.UserCriteria;
import cultu.common.message.UserScenario;
import cultu.common.service.UserManager;
import cultu.community.message.Community;
import cultu.core.message.JpqlParameter;
import cultu.customer.message.Customer;
import cultu.supplier.message.Association;
import cultu.supplier.message.Download;
import cultu.supplier.message.DownloadScenario;
import cultu.supplier.message.Product;
import cultu.supplier.message.ProductCriteria;
import cultu.supplier.message.ProductList;
import cultu.supplier.message.ProductScenario;
import cultu.supplier.service.DownloadManager;
import cultu.supplier.service.DownloadService;
import cultu.supplier.service.ProductService;

/**
 * The download service.
 * @author Marc-Antoine
 *
 */
public class DownloadServiceImpl implements DownloadService
{

  /**
   * User manager.
   */
  private UserManager userManager;
  
  /**
   * Product service.
   */
  private ProductService productService;
  
  /**
   * The download manager.
   */
  private DownloadManager downloadManager;
  
  /**
   * @param userManager the userManager to set
   */
  public void setUserManager(UserManager userManager)
  {
    this.userManager = userManager;
  }

  /**
   * @param productService the productService to set
   */
  public void setProductService(ProductService productService)
  {
    this.productService = productService;
  }

  /**
   * @param downloadManager the downloadManager to set
   */
  public void setDownloadManager(DownloadManager downloadManager)
  {
    this.downloadManager = downloadManager;
  }

  /**
   * {@inheritDoc}
   */
  @Transactional(readOnly = true)
  public Download createDownload(final User user, final Product product) {
   
    // Get User.     
    final User userDb = userManager.getUser(null, new UserScenario(), user);
    
    // Get product.
    final Product productDb = productService.getProductById(product.getHjid());
    
    if (userDb != null && productDb != null) {
      // Persist download.
      
      Download download = new Download();
      download.setKey(RandomStringUtils.randomAlphanumeric(16));
      download.setProduct(productDb);
      download.setUser(userDb);
      download.setExpired(false);
      download.setDownloaded(false);
      
      return downloadManager.createDownload(null, new DownloadScenario(), download);
    }
    
    return null;
  }

}
